<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="起运站" prop="startOrgId">
        <el-select v-model="queryParams.startOrgId" clearable filterable placeholder="请选择起运站" @keyup.enter.native="handleQuery">
          <el-option v-for="dict in dict.type.DB_JC_ORG" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="目的站" prop="endOrgId">
        <el-select v-model="queryParams.endOrgId" clearable filterable placeholder="请选择目的站" @keyup.enter.native="handleQuery">
          <el-option v-for="dict in dict.type.DB_JC_ORG" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="车牌" prop="license">
        <el-input
          v-model="queryParams.license"
          clearable
          placeholder="请输入车牌"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发货时间">
        <el-date-picker
          v-model="daterangeSendDate"
          end-placeholder="结束日期"
          range-separator="-"
          start-placeholder="开始日期"
          style="width: 240px"
          type="daterange"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="到达时间">
        <el-date-picker
          v-model="daterangeReceiveDate"
          end-placeholder="结束日期"
          range-separator="-"
          start-placeholder="开始日期"
          style="width: 240px"
          type="daterange"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['backGoods:backGoods:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['backGoods:backGoods:edit']"
          :disabled="single"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['backGoods:backGoods:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['backGoods:backGoods:export']"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="backGoodsList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="编号" prop="code" width="120"/>
      <el-table-column align="center" label="起运站" prop="startOrgName"/>
      <el-table-column align="center" label="目的站" prop="endOrgName"/>
      <el-table-column align="center" label="车牌" prop="license"/>
      <el-table-column align="center" label="返货理由" prop="reason"/>
      <el-table-column align="center" label="数量" prop="totalQuantity"/>
      <el-table-column align="center" label="体积" prop="totalVolume"/>
      <el-table-column align="center" label="重量" prop="totalWeight"/>
      <el-table-column align="center" label="状态" prop="status">
        <template #default="scope">
          <dict-tag :options="dict.type.back_goods_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发货时间" prop="sendDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.sendDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="到达时间" prop="receiveDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.receiveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人" prop="createName"/>
      <el-table-column align="center" label="创建时间" prop="createTime" width="180" />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="200">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 'created'"
            v-hasPermi="['backGoods:backGoods:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.status === 'created'"
            v-hasPermi="['backGoods:backGoods:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleSend(scope.row)"
          >发货
          </el-button>
          <el-button
            v-if="scope.row.status === 'sended'"
            v-hasPermi="['backGoods:backGoods:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleReceive(scope.row)"
          >到达
          </el-button>

          <el-button
            v-if="scope.row.status === 'created'"
            v-hasPermi="['backGoods:backGoods:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改内部返货对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="起运站" prop="startOrgId">
              <el-select v-model="form.startOrgId" clearable filterable placeholder="请选择起运站">
                <el-option v-for="dict in dict.type.DB_JC_ORG" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目的站" prop="endOrgId">
              <el-select v-model="form.endOrgId" clearable filterable placeholder="请选择目的站">
                <el-option v-for="dict in dict.type.DB_JC_ORG" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌" prop="license">
              <el-input v-model="form.license" placeholder="请输入车牌" maxlength="8" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="返货理由" prop="reason">
              <el-input v-model="form.reason" placeholder="请输入返货理由"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="totalQuantity">
              <el-input v-model="form.totalQuantity" placeholder="请输入数量" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体积" prop="totalVolume">
              <el-input v-model="form.totalVolume" placeholder="请输入体积" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重量" prop="totalWeight">
              <el-input v-model="form.totalWeight" placeholder="请输入重量" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="发货时间" prop="sendDate">
              <el-date-picker v-model="form.sendDate"
                              clearable
                              placeholder="请选择发货时间"
                              type="date"
                              value-format="yyyy-MM-dd HH:mm:ss" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到达时间" prop="receiveDate">
              <el-date-picker v-model="form.receiveDate"
                              clearable
                              placeholder="请选择到达时间"
                              type="date"
                              value-format="yyyy-MM-dd HH:mm:ss" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input v-model="form.description" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">返货详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button icon="el-icon-plus" size="mini" type="primary" @click="handleAddJcBackGoodsItem">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="el-icon-delete" size="mini" type="danger" @click="handleDeleteJcBackGoodsItem">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table ref="jcBackGoodsItem" :data="jcBackGoodsItemList" :row-class-name="rowJcBackGoodsItemIndex" @selection-change="handleJcBackGoodsItemSelectionChange">
          <el-table-column align="center" type="selection" width="50"/>
          <el-table-column align="center" label="序号" prop="index" width="50"/>
          <el-table-column label="客户名称" prop="customerName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.customerName" placeholder="请输入客户名称"/>
            </template>
          </el-table-column>
          <el-table-column label="货品名称" prop="productName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入货品名称"/>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity">
            <template #default="scope">
              <el-input type="number" v-model="scope.row.quantity" placeholder="请输入数量"/>
            </template>
          </el-table-column>
          <el-table-column label="体积" prop="volume">
            <template #default="scope">
              <el-input type="number" v-model="scope.row.volume" placeholder="请输入体积"/>
            </template>
          </el-table-column>
          <el-table-column label="重量" prop="weight">
            <template #default="scope">
              <el-input type="number" v-model="scope.row.weight" placeholder="请输入重量"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    发货并上传照片-->
    <el-dialog :title="title" v-model="openSend" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <image-upload v-model="form.sendImgs"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="this.openSend=false">取 消</el-button>
      </div>
    </el-dialog>
    <!--    到货并上传照片-->
    <el-dialog :title="title" v-model="openReceive" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <image-upload v-model="form.receiveImgs"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="this.openReceive=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listBackGoods, getBackGoods, delBackGoods, addBackGoods, updateBackGoods} from "@/api/backGoods/backGoods";

export default {
  name: "BackGoods",
  dicts: ["DB_JC_ORG", 'back_goods_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedJcBackGoodsItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 内部返货表格数据
      backGoodsList: [],
      // 返货详情表格数据
      jcBackGoodsItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 重量时间范围
      daterangeSendDate: [],
      // 重量时间范围
      daterangeReceiveDate: [],
      // 重量时间范围
      daterangeCreateTime: [],
      // 重量时间范围
      daterangeModifyTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startOrgId: null,
        endOrgId: null,
        license: null,
        reason: null,
        totalQuantity: 0,
        totalVolume: 0,
        totalWeight: 0,
        status: null,
        sendDate: null,
        receiveDate: null,
        createName: null,
        modifyName: null,
        modifyTime: null,
        description: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        startOrgId: [
          {required: true, message: "起运站不能为空", trigger: "blur"}
        ],
        endOrgId: [
          {required: true, message: "目的站不能为空", trigger: "blur"}
        ],
        license: [
          {required: true, message: "车牌不能为空", trigger: "blur"}
        ],
        reason: [
          {required: true, message: "返货理由不能为空", trigger: "blur"}
        ]
      },
      openSend: false,
      openReceive: false,
    };
  },
  watch: {
    // 监听 jcBackGoodsItemList 数据变化，计算总数量、总体积、总重量
    jcBackGoodsItemList: {
      handler: function (newVal, oldVal) {
        let totalQuantity = 0;
        let totalVolume = 0;
        let totalWeight = 0;
        newVal.forEach(item => {
          totalQuantity += Number(item.quantity);
          totalVolume += Number(item.volume);
          totalWeight += Number(item.weight);
        });
        this.form.totalQuantity = totalQuantity;
        this.form.totalVolume = totalVolume;
        this.form.totalWeight = totalWeight;
      },
      deep: true
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询内部返货列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeSendDate && '' != this.daterangeSendDate) {
        this.queryParams.params["beginSendDate"] = this.daterangeSendDate[0];
        this.queryParams.params["endSendDate"] = this.daterangeSendDate[1];
      }
      if (null != this.daterangeReceiveDate && '' != this.daterangeReceiveDate) {
        this.queryParams.params["beginReceiveDate"] = this.daterangeReceiveDate[0];
        this.queryParams.params["endReceiveDate"] = this.daterangeReceiveDate[1];
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeModifyTime && '' != this.daterangeModifyTime) {
        this.queryParams.params["beginModifyTime"] = this.daterangeModifyTime[0];
        this.queryParams.params["endModifyTime"] = this.daterangeModifyTime[1];
      }
      listBackGoods(this.queryParams).then(response => {
        this.backGoodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        startOrgId: null,
        endOrgId: null,
        license: null,
        reason: null,
        totalQuantity: 0,
        totalVolume: 0,
        totalWeight: 0,
        status: null,
        sendDate: null,
        receiveDate: null,
        createName: null,
        createTime: null,
        modifyName: null,
        modifyTime: null,
        description: null
      };
      this.jcBackGoodsItemList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeSendDate = [];
      this.daterangeReceiveDate = [];
      this.daterangeCreateTime = [];
      this.daterangeModifyTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加内部返货";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBackGoods(id).then(response => {
        this.form = response.data;
        this.jcBackGoodsItemList = response.data.jcBackGoodsItemList;
        this.open = true;
        this.title = "修改内部返货";
      });
    },
    handleSend(row) {
      this.openSend = true;
      this.form = Object.assign({}, row);
    },
    handleReceive(row) {
      this.openReceive = true;
      this.form = Object.assign({}, row);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        // jcBackGoodsItemList 数据不能为空
        if (this.jcBackGoodsItemList.length === 0) {
          this.$modal.msgError("返货详情数据不能为空");
          return;
        }
        // jcBackGoodsItemList 中的 customerName、 productName、quantity 不能为空
        let validItem = false;
        for (let i = 0; i < this.jcBackGoodsItemList.length; i++) {
          if (this.jcBackGoodsItemList[i].customerName === '' || this.jcBackGoodsItemList[i].productName === '' || this.jcBackGoodsItemList[i].quantity === '') {
            validItem = true;
            break;
          }
        }
        if (validItem) {
          this.$modal.msgError("返货详情数据不能为空");
          return;
        }
        if (valid) {
          this.form.jcBackGoodsItemList = this.jcBackGoodsItemList;
          if (this.form.id != null) {
            updateBackGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBackGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除内部返货编号为"' + ids + '"的数据项？').then(function () {
        return delBackGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 返货详情序号 */
    rowJcBackGoodsItemIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 返货详情添加按钮操作 */
    handleAddJcBackGoodsItem() {
      let obj = {};
      obj.customerId = null;
      obj.customerName = "";
      obj.productName = "";
      obj.quantity = 0;
      obj.volume = 0;
      obj.weight = 0;
      this.jcBackGoodsItemList.push(obj);
    },
    /** 返货详情删除按钮操作 */
    handleDeleteJcBackGoodsItem() {
      if (this.checkedJcBackGoodsItem.length == 0) {
        this.$modal.msgError("请先选择要删除的返货详情数据");
      } else {
        const jcBackGoodsItemList = this.jcBackGoodsItemList;
        const checkedJcBackGoodsItem = this.checkedJcBackGoodsItem;
        this.jcBackGoodsItemList = jcBackGoodsItemList.filter(function (item) {
          return checkedJcBackGoodsItem.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleJcBackGoodsItemSelectionChange(selection) {
      this.checkedJcBackGoodsItem = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('backGoods/backGoods/export', {
        ...this.queryParams
      }, `backGoods_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
